#include "../source/log.h"
#include "../source/io_manager.h"
#include <iostream>
#include <asm-generic/errno.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <thread>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <sys/epoll.h>

void test_fiber()
{
    log_debug("test fiber");

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    fcntl(sock, F_SETFL, O_NONBLOCK); //O_NONBLOCK 设置I/O为非阻塞模式

    sockaddr_in addr;
    memset(&addr, 0, sizeof(sockaddr_in));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr.s_addr);

    if(!connect(sock, (const sockaddr*)&addr, sizeof(addr)))
    {
        log_error("connect error");
        return;
    }

    IOManager::GetThis()->addEvent(sock, IOManager::READ, [](){
        log_debug("read callback");
    });
    IOManager::GetThis()->addEvent(sock, IOManager::WRITE, [sock](){
        log_debug("wirte callback");
        //close(sock);
        // IOManager::GetThis()->cancelEvent(sock, IOManager::READ);
        // close(sock);
    });

}

void test1()
{
    IOManager iom;
    iom.schedule(test_fiber);
}

Timer::ptr g_task;
void test_timer()
{
    IOManager iom(3);
    g_task = iom.addTimer(500, [&](){
    
        log_debug("hello world thread id = {}", Scheduler::GetThreadId(std::this_thread::get_id()));
    
        static int i = 5;
        if(--i < 0)
        {
            // task->cancel();
            g_task->resetTimer(2000, false);
        }

    }, true);

    // log_critical("sloop 5s");
    // sleep(5);
    // task->cancel();
}

int main(void)
{
    // test1();
    test_timer();

    return 0;
}